package com.cloudcc.mobile.view.schedule;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.log.Log;
import com.mypage.adapter.NewRelatedAdapter;
import com.mypage.bean.NewTaskBean;
import com.mypage.utils.UtilsShowDialog;

public class NewRelatedActivity extends Activity implements
        TextView.OnEditorActionListener {
    private String mEns = RunTimeManager.getInstance().getlanguage();
    public static NewRelatedActivity instance = null;
    private TextView bar_title_text;
    private Button mBtnBack;
    private ListView relateListView;
    private NewTaskBean mDdata;
    private EditText mSearch;
    private String mSearchData = "";
    private UtilsShowDialog showDialog;
    private TextView relateNoData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_relate);
        showDialog = new UtilsShowDialog(this);
        instance = this;
        mSearch = (EditText) findViewById(R.id.mSearch);
        mSearch.setOnEditorActionListener(this);
        bar_title_text = (TextView) findViewById(R.id.bar_title_text);
        relateNoData = (TextView) findViewById(R.id.relateNoData);
        if ("en".equals(mEns)) {
            bar_title_text.setText("Related items");
        } else {
            bar_title_text.setText("相关项");
        }

        initView();
        initListener();
        getHttp();
    }

    private void initView() {
        // TODO Auto-generated method stub
        if ("en".equals(mEns)) {
            showDialog.onShowLoadingDialog("loading...");
        } else {
            showDialog.onShowLoadingDialog("正在加载...");
        }

        mBtnBack = (Button) findViewById(R.id.mBtnBack);// 返回按钮
        relateListView = (ListView) findViewById(R.id.relateListView);
    }

    public void initListener() {
        mBtnBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
    }

    public void getHttp() {
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "getLookupobj");
        params.addBodyParameter("keyword", mSearchData);
        Log.d("状态url-------------------------", UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getLookupobj" + "&keyword=");
        utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        // TODO Auto-generated method stub
                        showDialog.onDismissLoadingDialog();
                        Toast.makeText(NewRelatedActivity.this, "接口调用失败", Toast.LENGTH_SHORT).show();
                        Log.d("相关项接口失败-------------------------", arg1);
                        nodata(true);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        Log.d("相关项接口成功-------------------------", arg0.result);
                        showDialog.onDismissLoadingDialog();
                        mDdata = new Gson().fromJson(arg0.result,
                                NewTaskBean.class);
                        if (!mDdata.result) {
                            if ("en".equals(mEns)) {
                                Toast.makeText(NewRelatedActivity.this, "Save failed", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(NewRelatedActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                            }

                        }
                        if(mDdata != null && ListUtils.isEmpty(mDdata.data)){
                            nodata(true);
                        }else{
                            nodata(false);
                            NewRelatedAdapter mAdapter = new NewRelatedAdapter(
                                    NewRelatedActivity.this, mDdata);
                            relateListView.setAdapter(mAdapter);
                        }

                    }

                });
        relateListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                intent.setClass(NewRelatedActivity.this, NewListActivity.class);
                intent.putExtra("ID", mDdata.data.get(position).objid);
                intent.putExtra("Name", mDdata.data.get(position).labelname);
                startActivityForResult(intent, 2);

            }
        });

    }

    private void nodata(boolean isnodata) {
        if (isnodata) {

            relateNoData.setVisibility(View.VISIBLE);
            relateListView.setVisibility(View.GONE);
        } else {
            relateNoData.setVisibility(View.GONE);
            relateListView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (null == data) {
            return;
        }
        if (2 == requestCode) {
            String mRelated = data.getStringExtra("AV");
            String mNames = data.getStringExtra("AVname");
//		if ("".equals(mRelated)) {
//			return;
//		}
            Intent mInt = new Intent();
            mInt.putExtra("AvA", mRelated);
            mInt.putExtra("AvAname", mNames);
            setResult(22, mInt);
            finish();

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            mSearchData = mSearch.getText().toString().trim();
            getHttp();
            // 当按了搜索之后关闭软键盘
            ((InputMethodManager) mSearch.getContext().getSystemService(
                    Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this
                            .getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
            return true;
        }
        return false;
    }
}
